<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/16
 * Time: 16:31
 */

namespace app\Utils;

use app\admin\model\System\SysPayModel;
use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;

class WechatPayUtil
{
    protected $config;
    protected $extend_json;

    public function __construct()
    {
        $wx = SysPayModel::getSysPayWhere([['id', '=', 3]]);
        $this->extend_json = json_decode($wx['extend_json'], true);
        $this->config = [
            'appid' => $this->extend_json['app_id'],
            'mch_id' => $this->extend_json['mch_id'],
            'key' => $this->extend_json['key'],
            'cert_client' => 'http://systudyad.shawyo.com/payment/weixin/cert/apiclient_cert.pem', // optional，退款等情况时用到
            'cert_key' => 'http://systudyad.shawyo.com/payment/weixin/cert/apiclient_key.pem',// optional，退款等情况时用到

        ];
    }

    /**
     * @param $out_trade_no
     * @param $total_fee
     * @param $body
     */
    public function wechat_pay($out_trade_no, $total_fee, $body, $type = 1)
    {
        switch ($type) {
            case 1:
                $this->config['notify_url'] = $this->extend_json['notify_url'];
                break;
            case 2:
                $this->config['notify_url'] = $this->extend_json['partner_notify_url'];
                break;
        }
        $order = [
            'out_trade_no' => $out_trade_no,
            'total_fee' => 1, // **单位：分**
            'body' => $body,
        ];
       return  json_decode(Pay::wechat($this->config)->app($order)->getContent(),true);

    }

    /**
     * 微信支付测试
     */
    public function wx_pay_ceshi()
    {
        $this->config['notify_url'] = $this->extend_json['notify_url'];
        $order = [
            'out_trade_no' => time(),
            'total_fee' => 1, // **单位：分**
            'body' => '测试',
        ];
        return  json_decode(Pay::wechat($this->config)->app($order)->getContent(),true);
    }

    /**
     * 微信退款
     */
    public function refund($total_fee, $out_trade_no, $desc = '商品退款')
    {
        $wechat = Pay::wechat($this->config);
        $order = [
            'out_trade_no' => $out_trade_no,
            'out_refund_no' => time(),
            'total_fee' => $total_fee,
            'refund_fee' => $total_fee,
            'refund_desc' => $desc,
        ];
        $result = $wechat->refund($order);
        return ['code' => 0, 'data' => '', 'msg' => ''];
    }
}